package com.ld.common.config;

import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.ld.shieldsb.common.core.model.PropertiesModel;
import com.ld.shieldsb.common.core.util.StringUtils;

@Configuration
public class UploadConfig implements WebMvcConfigurer {

    /**
     * 增加本地上传路径的支持
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String uploadPath = PropertiesModel.CONFIG.getString("shieldsb.upload.fileRootPath", "");
        String uploadFileDirPrefix = PropertiesModel.CONFIG.getString("shieldsb.upload.uploadFileDirPrefix", ""); // 为访问前缀，需要在uploadPath存在该目录
        if (StringUtils.isNotBlank(uploadPath)) {
            if (!uploadPath.endsWith("/")) {
                uploadPath += "/";
            }
            String[] prefixs = StringUtils.getStrArr(uploadFileDirPrefix);
            if (prefixs != null && prefixs.length > 0) {
                for (String prefix : prefixs) {
                    prefix = "/" + prefix + "/";
                    prefix = prefix.replaceAll("/+", "/"); // 去除多余的/
                    String resourceLocation = uploadPath + prefix;
                    resourceLocation = resourceLocation.replaceAll("/+", "/");
                    // 假设uploadPath 为F:/upload ，uploadFileDirPrefix为：ueditor
                    // F:/upload/ueditor/1521766052825044522.jpg的访问地址为
                    // http://127.0.0.1:8080[端口]/software-center[项目名]/ueditor/1521766052825044522.jpg
                    registry.addResourceHandler(prefix + "**").addResourceLocations("file:" + resourceLocation)
                            .setCacheControl(CacheControl.maxAge(10, TimeUnit.DAYS).cachePrivate());
                }

            }

        }
    }

}
